//
//  JQFYNetworkTool.m
//  JQFY
//
//  Created by apple on 2017/8/28.
//  Copyright © 2017年 yannis. All rights reserved.
//

#import "JQFYNetworkTool.h"
#import <Reachability.h>

@protocol NetworkToolsProxy <NSObject>

@optional
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(id)parameters
                                  uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
                                downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
                                         success:(void (^)(NSURLSessionDataTask *, id))success
                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure;


- (NSURLSessionDataTask *)POST:(NSString *)URLString
                    parameters:(nullable id)parameters
     constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
                      progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
                       success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                       failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;



@end

@interface JQFYNetworkTool()<NetworkToolsProxy>

@end

@implementation JQFYNetworkTool

+(instancetype)sharedManager{
    
    static JQFYNetworkTool *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        
        instance = [[self alloc]initWithBaseURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",BASEURL]] sessionConfiguration:config];
        
        //返回类型
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"image/jpeg",@"application/octet-stream",@"text/plain",@"application/pdf",@"application/x-msdownload",nil];
        
        instance.requestSerializer = [AFJSONRequestSerializer serializer];
        instance.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
        //超时
        instance.requestSerializer.timeoutInterval = 30.0;
        if (instance.requestSerializer.timeoutInterval > 60.0) {
            [MBProgressHUD showWithMessage:@"主人,网络连接超时~"];
        }
        
    });
    return instance;
}


- (void)request:(RequestMethod)method urlString:(NSString *)urlString parameters:(id)parameters finished:(void (^)(id, NSError *))finished{
    
    NSString *token = [[JQFYUserData userDataInSandbox] token];
    
    [self.requestSerializer setValue:[NSString stringWithFormat:@"%@",token] forHTTPHeaderField:@"token"];
    
    NSString *reqMethod = (method == RequestMethodGet) ? @"GET" : @"POST";
    
    [[self dataTaskWithHTTPMethod:reqMethod URLString:urlString parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *dataTask, id responseObject) {
        
//        finished(responseObject,nil);
        NSDictionary *msg = [responseObject valueForKey:@"msg"];
        NSString *status = [responseObject valueForKey:@"status"];
        if ([status isEqualToString:@"success"]) {
            finished(msg,nil);
        } else {
            NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"接口参数错误", nil)};
                NSError *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
            finished(nil,error);
        }
        
    } failure:^(NSURLSessionDataTask *dataTask, NSError *error) {
        // 请求失败
        
        NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
        
        NSInteger statusCode = response.statusCode;
        
        NSLog(@"statusCode = %ld",statusCode);
        
        if ( statusCode == 401) {
            
            JQFYUserData *data = [JQFYUserData userDataInSandbox];
            
            [data cleanUserInfo];
            [MBProgressHUD showWithMessage:@"登录失效,请重新登录"];
            
            [[NSNotificationCenter defaultCenter]postNotificationName:@"goToLogin" object:nil];
            
        } else {
            [MBProgressHUD showWithMessage:@"服务器异常"];
        }
        
        finished(nil, error);
        
    }] resume];
    
}

//检查网络连接
-(BOOL)isReachableByAFN{
    
    Reachability *reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    NSLog(@"isReachable = %d",reachability.isReachable);
        if (!reachability.isReachable) {
            //无权限 引导去开启
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
            }
        }
    
    return reachability.isReachable;
}

@end
